import React, { useRef, useState } from "react"
import { Image, ScrollView, View } from "@tarojs/components"
import Taro, { useRouter, useReachBottom, useDidShow } from "@tarojs/taro"
import GpContainer from "@/components/GpContainer"
import { NAVIGATION_BASE_LAYOUT, useNavigationOpacity, useSetState } from "@/utils/hooks"
import Icon from "@/components/GpFontIcon"
import styles from "./index.module.scss"
import GpVerticelLine from "@/components/GpVerticelLine"
import GpFlowModule from "../../note/components/GpFlowModule"
import clsx from "clsx"
import GpWordItem from "../../note/components/GpWordItem"
import ImageCascade from "../components/imageCascade"
import {
  getIndexData,
  getTopicDetail,
  getTopicRelatedNotes,
  switchWordCollect
} from "@/apis/yikao-community"
import { requestIsFullfilled } from "@/utils/request"
import { MenuContentType } from "@/types/enum"
import { handleBlockNavigation } from "@/utils/app"
import GpScrollLoading from "@/components/GpScrollLoading"
import NoteAnswer from "../components/noteAnswer"
import { useAppSelector } from "@/store/hook"
import GpChatActionPopup from "@/components/GpChatActionPopup"
import GpNavbar from "@/components/GpNavbar"

type IState = {
  currentFilter: number
  openActionPopup: boolean
  detailData: IApiRelative.IGetTopicDetail.IResData
  /** 相关推荐
   * @description 对应首页的专题模块
   */
  contentSpecials: (IApiRelative.IGetIndexData.MenuItem & { className: string })[]
  /** 话题关联的笔记列表 */
  noteList: IApiRelative.IGetTopicRelatedNotes.ITopicRelatedNote[]
  /** 是否有更多关联笔记 */
  hasMoreNote: boolean
  /** 页码 */
  noteCurrent: number
}
type IParams = /** 话题id */ PrimaryKey<string>
/**
 * @page 话题详情
 */
export default function WordDetail() {
  const authInfo = useAppSelector(state => state.auth.userInfo)
  const params = useRouter<IParams>().params
  const filters = useRef<IOptionLike<number>[]>([
    { value: 0, label: "推荐" },
    { value: 1, label: "最新" }
  ])
  const [layout, setLayout] = useState<NavigationBaseLayout>(NAVIGATION_BASE_LAYOUT)
  const [state, setState, stateRef] = useSetState<IState>(
    {
      currentFilter: filters.current[0].value,
      openActionPopup: false,
      detailData: {
        /** 关联模块  */
        modules: [],
        /** 推荐话题 */
        recommendDiscussions: []
      } as unknown as IApiRelative.IGetTopicDetail.IResData,
      contentSpecials: [],
      hasMoreNote: true,
      noteCurrent: 1,
      noteList: []
    },
    true
  )
  const [navigationOpacity] = useNavigationOpacity()
  useReachBottom(() => {
    if (stateRef.current?.hasMoreNote) {
      setState({
        noteCurrent: stateRef.current?.noteCurrent + 1
      })
      searchNoteList()
    }
  })
  useDidShow(() => {
    fetchDetailData()
    fetchRelatedRecommands()
    searchNoteList()
  })
  function searchNoteList() {
    if (!stateRef.current) return
    getTopicRelatedNotes(
      {
        id: params.id
      },
      {
        pagination: {
          current: stateRef.current.noteCurrent,
          pageSize: 10
        },
        search: {},
        sort: {
          predicate: stateRef.current.currentFilter === 1 ? "updatedTime" : "",
          reverse: stateRef.current.currentFilter === 1
        }
      }
    ).then(res => {
      if (requestIsFullfilled(res)) {
        const { list, pagination } = res.data.data
        setState({
          hasMoreNote: pagination.current < pagination.pageCount,
          noteList: pagination.current === 1 ? list : stateRef.current?.noteList.concat(list)
        })
      }
    })
  }
  /** 获取相关推荐 */
  function fetchRelatedRecommands() {
    getIndexData().then(data => {
      if (requestIsFullfilled(data)) {
        const contentSpecials: IState["contentSpecials"] = []
        const contentSpecialsTypes = [
          MenuContentType.ContentSpecial1,
          MenuContentType.ContentSpecial2,
          MenuContentType.ContentSpecial3,
          MenuContentType.ContentSpecial4,
          MenuContentType.ContentSpecial5,
          MenuContentType.ContentSpecial6
        ]
        for (const menu of data.data.data.menus) {
          if (contentSpecialsTypes.includes(menu.type)) {
            let className = ""
            switch (menu.type) {
              case MenuContentType.ContentSpecial1:
                className = "inner_1"
                break
              case MenuContentType.ContentSpecial2:
                className = "inner_2"
                break
              case MenuContentType.ContentSpecial3:
                className = "inner_3"
                break
              case MenuContentType.ContentSpecial4:
                className = "inner_4"
                break
              case MenuContentType.ContentSpecial5:
                className = "inner_5"
                break
              case MenuContentType.ContentSpecial6:
                className = "inner_6"
                break
              default:
                break
            }
            contentSpecials.push({
              ...menu,
              className
            })
          }
        }
        setState({ contentSpecials })
      }
    })
  }
  /** 获取话题详情 */
  function fetchDetailData() {
    if (params.id) {
      Taro.showLoading({ title: "加载中" })
      getTopicDetail({ id: params.id })
        .then(res => {
          if (requestIsFullfilled(res)) {
            setState({ detailData: res.data.data })
          }
        })
        .finally(() => Taro.hideLoading())
    }
  }
  function handleFilterChange(filter: number) {
    if (state.currentFilter === filter) return
    setState({ currentFilter: filter, noteCurrent: 1 })
    searchNoteList()
  }
  function handleNoteLikeSuccess(noteId: number, meta: IApiRelative.INoteLikeSwitch.IResData) {
    const { isLike, likeCount } = meta
    const _list = state.noteList.concat()
    const _note = _list.find(item => item.id === noteId)
    if (_note) {
      _note.isSelfLike = isLike
      _note.likeCount = likeCount
      setState({ noteList: _list })
    }
  }
  function handleCollect() {
    switchWordCollect({ id: params.id }).then(res => {
      if (requestIsFullfilled(res)) {
        Taro.showToast({
          title: state.detailData.isCollected ? "已取消收藏" : "收藏成功",
          icon: "none"
        })
        const _detailData = Object.assign({}, state.detailData)
        _detailData.isCollected = !_detailData.isCollected
        setState({ detailData: _detailData })
      }
    })
  }
  function renderNavigation() {
    return (
      <GpNavbar
        navigationBarPlaceholder={false}
        navigationBarBackgroundColor={`rgba(255,255,255,${navigationOpacity})`}
        arrowLeftProps={{
          color:
            navigationOpacity > 0.5
              ? `rgba(51, 51, 51, ${navigationOpacity})`
              : `rgba(255, 255, 255, ${1 - navigationOpacity})`
        }}
        onLayout={setLayout}
      />
    )
  }
  function renderTopInfo() {
    return (
      <View className={styles.topInfo}>
        <View className={styles.bgWrap}>
          <Image src={state.detailData.thumbnail} className={styles.bg} mode="widthFix" />
        </View>
        <View
          style={{
            position: "absolute",
            background: "rgba(0, 0, 0, 0.4)",
            left: 0,
            top: 0,
            right: 0,
            bottom: 0,
            zIndex: 0
          }}
        ></View>
        <View
          style={{
            paddingTop: layout.statusBarHeight + layout.navigationHeight + "px"
          }}
          className="relative z-30 px-32px"
        >
          <View className={styles.topicTitle}>#&nbsp;{state.detailData.title}</View>
          <View className={styles.topicInfo}>
            <ImageCascade size={44} className="mr-8px" images={state.detailData.miniVisitorHeads} />
            <View className={styles.topicView}>{state.detailData.viewCount}人浏览</View>
            <GpVerticelLine
              color="#FFFFFF"
              width={2}
              height={28}
              className="mx-16px inline-block"
            />
            <View className={styles.topicView}>{state.detailData.participantCount}人参与</View>
            <View
              className={clsx(styles.colloct, {
                [styles.collocted]: state.detailData.isCollected
              })}
              onClick={handleCollect}
            >
              {/* 已收藏图标 */}
              {/* <Icon icon="icon-shoucang-yixuanzhong" color="#FA3F29" size={32} /> */}
              {state.detailData.isCollected ? null : (
                <Icon icon="icon-shoucang" color="#FFFFFF" size={32} />
              )}
              {state.detailData.isCollected ? "已收藏" : "收藏"}
            </View>
          </View>
        </View>
      </View>
    )
  }
  function renderFlowModule() {
    if (!state.detailData.modules || state.detailData.modules.length === 0) return null
    const flowModule = state.detailData.modules[0]
    return (
      <GpFlowModule
        className="mt-32px"
        flowModule={{
          remark: flowModule.remark,
          title: flowModule.name,
          description: flowModule.description,
          displayName: flowModule.displayName,
          image: flowModule.cover,
          id: flowModule.id,
          jumpPageId: flowModule.jumpPageId,
          jumpPageType: flowModule.jumpPageType,
          jumpType: flowModule.jumpType,
          jumpUrl: flowModule.jumpUrl,
          isHide: flowModule.isHide
        }}
      />
    )
  }
  function renderTopDesc() {
    return (
      <View className={styles.topicDesc}>
        <View className={styles.topicDescLabel}>话题背景</View>
        <View className={styles.topicDescContent}>{state.detailData.description}</View>
        {/* 引流模块 */}
        {renderFlowModule()}
      </View>
    )
  }
  /** 渲染话题关联的笔记列表 */
  function renderList() {
    return (
      <View className="box-border px-32px bg-page pb-32px">
        <View className="flex flex-row items-center box-border h-104px gap-24px">
          {filters.current.map(l => (
            <View
              key={l.value}
              className={clsx(styles.filter, {
                [styles.filterActive]: l.value === state.currentFilter
              })}
              onClick={() => handleFilterChange(l.value)}
            >
              {l.label}
            </View>
          ))}
        </View>
        <View className="box-border flex flex-col gap-16px">
          {/* list item for loop */}
          {state.noteList.map(l => (
            <NoteAnswer
              key={l.id}
              note={l}
              onLike={handleNoteLikeSuccess}
              className="rounded-16px pt-34px px-32px pb-32px"
              from="worddetail"
              topicId={params.id}
            />
          ))}
        </View>
      </View>
    )
  }
  function renderBottom() {
    const contentSpecials = state.contentSpecials
    const hasDiscussions =
      state.detailData.recommendDiscussions && state.detailData.recommendDiscussions.length > 0
    const hasSpecials = contentSpecials.length > 0
    if (!hasDiscussions && !hasSpecials) return null
    return (
      <View className={styles.bottomInfo}>
        {hasDiscussions ? (
          <View className="px-32px">
            <View className="text-32px text-bold font-500 box-border py-34px">相关话题</View>
            <View className="flex flex-row justify-start flex-wrap box-border gap-16px">
              {state.detailData.recommendDiscussions.map(l => (
                <GpWordItem
                  key={l.id}
                  wordItem={{
                    id: l.id,
                    name: l.title
                  }}
                />
              ))}
            </View>
          </View>
        ) : null}
        {hasSpecials ? (
          <View className="box-border">
            {/* 当有相关话题时, 相关推荐距离相关话题间距64px(30 + 34) */}
            {hasDiscussions && <View className="h-30px box-border"></View>}
            <View className="text-32px px-32px text-bold font-500 box-border py-34px">
              相关推荐
            </View>
            <ScrollView
              scrollX
              className={styles.contentSpecials}
              style={{
                marginTop: 0
              }}
            >
              {contentSpecials.map(l => (
                <View
                  className={styles.contentSpecial}
                  key={l.id}
                  onClick={() => handleBlockNavigation(l)}
                >
                  <View className={clsx(styles.inner, styles[l.className])}>
                    <View className={styles.innerTitle}>{l.name}</View>
                    <View className={styles.innerDesc}>{l.description}</View>
                  </View>
                </View>
              ))}
            </ScrollView>
          </View>
        ) : null}
      </View>
    )
  }
  function renderAction() {
    return (
      <View
        onClick={() => setState({ openActionPopup: true })}
        className="box-border w-238px h-96px bg-primary gap-32px rounded-48px flex flex-row justify-start pl-18px items-center fixed bottom-120px left-246px right-246px"
        style={{
          boxShadow: "0 0 16px 0 #00000029"
        }}
      >
        <View className={styles.headImageWrap}>
          <Image
            src={authInfo.headImage || process.env.__DEF_AVATAR__}
            className="w-64px h-64px rounded-full object-cover block"
          />
        </View>
        <View className="text-white text-36px font-700">表态</View>
      </View>
    )
  }
  function renderActionPopup() {
    return (
      <GpChatActionPopup
        open={state.openActionPopup}
        closeFn={() => setState({ openActionPopup: false })}
        topicId={Number(params.id)}
      />
    )
  }
  function renderListLoadingOrRest() {
    if (state.hasMoreNote) {
      return <GpScrollLoading />
    } else {
      return renderBottom()
    }
  }
  return (
    <GpContainer
      className="min-h-screen"
      pageGap={280}
      style={{
        backgroundColor: "#ffffff"
      }}
      shareConfig={{
        title: state.detailData.title
      }}
    >
      {renderNavigation()}
      {renderTopInfo()}
      {renderTopDesc()}
      {renderList()}
      {renderListLoadingOrRest()}
      {renderAction()}
      {renderActionPopup()}
    </GpContainer>
  )
}
